package com.jiantong.web.open.component;

import com.jiantong.user.enums.LoginType;
import com.jiantong.user.model.User;
import com.jiantong.user.service.UserReadService;
import com.jiantong.web.constants.SmsCodeType;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Author:cp
 * Created on 9/6/16.
 */
@Component
@Slf4j
public class MobileChecker {

    @RpcConsumer
    private UserReadService<User> userReadService;

    public void checkMobileExistedBySmsCodeType(String mobile, SmsCodeType smsCodeType) {
        Response<Boolean> checkResp = userReadService.checkExist(mobile, LoginType.MOBILE);
        if (!checkResp.isSuccess()) {
            log.error("fail to check mobile:{} if existed,cause:{}",
                    mobile, checkResp.getError());
            throw new OPServerException(checkResp.getError());
        }
        boolean isExisted = checkResp.getResult();

        switch (smsCodeType) {
            case USER_SIGN:
            case CHANGE_MOBILE:
                if (isExisted) {
                    throw new OPClientException("mobile.existed");
                }
                break;
            case FORGOT_PASSWORD:
                if (!isExisted) {
                    throw new OPClientException("mobile.not.existed");
                }
                break;
            default:
                throw new IllegalArgumentException("unknown sms code type:" + smsCodeType);
        }

    }

}
